﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SaleSoft.Models;
using SaleSoft.Helper;
using SaleSoft.Constants;
using Telerik.Web.Mvc;

namespace SaleSoft.Areas.administrator.Controllers
{
    public class AlbumController : BaseController {
        #region Properties Section
        private SaleSoftEntities db = new SaleSoftEntities();
        #endregion

        #region Views Section

        public ViewResult Index()
        {
            ViewData["error"] = this.TempData["error"];
            var ds_ablum = db.ds_ablum;
            return View(ds_ablum.ToList());
        }

        public ActionResult Create()
        {
            
            return View();
        }

        public ActionResult Edit ( int id ) {
            ds_ablum ds_ablum = db.ds_ablum.Single(d => d.id_ablum == id);
            
            return View(ds_ablum);
        }

        public ActionResult Images ( int id ) {
            Models.BaseClient.ds_album albumClient = new Models.BaseClient.ds_album();
            ds_ablum album = db.ds_ablum.Single(p => p.id_ablum == id);
            ObjectHelper.Copy(album, albumClient);
            var hinhanh = db.ds_hinhanh.Where(p => p.id_ablum == id);
            foreach (ds_hinhanh ha in hinhanh) {
                Models.BaseClient.ds_hinhanh hinhanhClient = new Models.BaseClient.ds_hinhanh();
                ObjectHelper.Copy(ha, hinhanhClient);
                albumClient.HinhAnh.Add(hinhanhClient);
            }
            Session[ScreenClientConstants.CURRENT_ALBUM] = albumClient;
            return View(albumClient);
        }

        [GridAction]
        public ActionResult _Images () {
            SaleSoft.Models.BaseClient.ds_album album = new Models.BaseClient.ds_album();
            if((SaleSoft.Models.BaseClient.ds_album)Session[ScreenClientConstants.CURRENT_ALBUM] != null){
                album = (SaleSoft.Models.BaseClient.ds_album)Session[ScreenClientConstants.CURRENT_ALBUM];
            }
            return View(new GridModel(album.HinhAnh));
        }
        #endregion

        #region CRUD Section

        [HttpPost]
        public ActionResult Create ( Models.BaseClient.ds_album ds_ablum, HttpPostedFileBase img )
        {
            if (ModelState.IsValid)
            {
                //Save image: accept png and jpg file only
                if (img != null && img.ContentLength > 0) {
                    if (img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".jpg" && img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".png") {
                        ViewData["error"] = "Accept JPGE and PNG file only";
                        return View(ds_ablum);
                    }
                    string dt = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                    string fName = ObjectHelper.ConvertToUnSign(ds_ablum.tenablum) + dt + img.FileName.Substring(img.FileName.LastIndexOf("."));
                    string SaveLocation = Server.MapPath("~\\UploadImages\\");
                    try {
                        img.SaveAs(SaveLocation + fName);   //save new file
                        ds_ablum.anhbia = fName;              //save file name to entity                    
                    } catch (Exception e) { ViewData["error"] = e.Message; return View(ds_ablum); }
                }
                ds_ablum.ngaycapnhat = DateTime.Now;
                ds_ablum save = new Models.ds_ablum();
                ObjectHelper.Copy(ds_ablum, save);
                db.ds_ablum.AddObject(save);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(ds_ablum);
        }

        [HttpPost]
        public ActionResult Edit (Models.BaseClient.ds_album ds_ablum , HttpPostedFileBase img) {
            if (ModelState.IsValid) {
                ds_ablum old = db.ds_ablum.Single(p => p.id_ablum == ds_ablum.id_ablum);
                db.ds_ablum.Detach(old);
                ds_ablum.ngaycapnhat = old.ngaycapnhat;
                if (img == null || img.ContentLength == 0) { // khong lam gi ca
                    ds_ablum.anhbia = old.anhbia;
                } else if (old.anhbia == null && img != null && img.ContentLength > 0) { // hinh cu khong co, luu hinh moi
                    //save image
                    if (img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".jpg" && img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".png") {
                        ViewData["error"] = "Accept JPGE and PNG file only";
                        return View(ds_ablum);
                    }
                    string dt = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                    string fName = ObjectHelper.ConvertToUnSign(img.FileName) + dt + img.FileName.Substring(img.FileName.LastIndexOf("."));
                    string SaveLocation = Server.MapPath("~\\UploadImages\\");
                    try {
                        img.SaveAs(SaveLocation + fName);   //save new file
                        ds_ablum.anhbia = fName;              //save file name to entity                    
                    } catch (Exception e) { ViewData["error"] = e.Message; return View(ds_ablum); }
                } else if (old.anhbia != null && img != null && img.ContentLength > 0) { // co hinh cu, co hinh moi 
                    string oldFile = Server.MapPath("/UploadImages/") + old.anhbia;
                    //xoa file cu
                    if (System.IO.File.Exists(oldFile)) {
                        try {
                            System.IO.File.Delete(oldFile);
                        } catch (Exception) {
                        }
                    }
                    //luu file moi
                    if (img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".jpg" && img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".png") {
                        ViewData["error"] = "Accept JPGE and PNG file only";
                        return View(ds_ablum);
                    }
                    string dt = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                    string fName = ObjectHelper.ConvertToUnSign(ds_ablum.anhbia) + dt + img.FileName.Substring(img.FileName.LastIndexOf("."));
                    string SaveLocation = Server.MapPath("~\\UploadImages\\");
                    try {
                        img.SaveAs(SaveLocation + fName);   //save new file
                        ds_ablum.anhbia = fName;              //save file name to entity                    
                    } catch (Exception e) { ViewData["error"] = e.Message; return View(ds_ablum); }
                }
                ds_ablum.ngaycapnhat = DateTime.Now;

                ds_ablum save = db.ds_ablum.Single(o => o.id_ablum == ds_ablum.id_ablum);
                ObjectHelper.Copy(ds_ablum, save);
                db.ObjectStateManager.ChangeObjectState(save, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(ds_ablum);
        }

        public ActionResult Delete ( int id ) {
            ds_ablum ds_ablum = db.ds_ablum.Single(d => d.id_ablum == id);
            if (ds_ablum.ds_hinhanh.Count > 0) {
                this.TempData["error"] = "Xóa các trong album trước!";
            } else if (ds_ablum.ds_noidungweb.Count > 0) {
                this.TempData["error"] = "Xóa các nội dung web có liên quan đến album này trước!";
            } else if (ds_ablum.ds_webmau.Count > 0) {
                this.TempData["error"] = "Xóa các web mẫu có liên quan đến album này trước!";
            } else {
                //Delete image
                string path = Server.MapPath("~//UploadImages//") + ds_ablum.anhbia;
                FileHelper.DeleteFile(path);
                db.ds_ablum.DeleteObject(ds_ablum);
                db.SaveChanges();
            }
            return RedirectToAction("index");
        }

        [HttpPost]
        public void UploadAlbumPhoto ( IEnumerable<HttpPostedFileBase> UploadPhotos ) {
            SaleSoft.Models.BaseClient.ds_album album = (SaleSoft.Models.BaseClient.ds_album)Session[ScreenClientConstants.CURRENT_ALBUM];
            string location = Server.MapPath("~\\UploadImages\\");
            string filename = "ITSKILL_" + album.id_ablum.ToString() + "_";
            foreach (HttpPostedFileBase file in UploadPhotos) {
                if (file.FileName.Substring(file.FileName.LastIndexOf(".")).ToLower() != ".jpg" && file.FileName.Substring(file.FileName.LastIndexOf(".")).ToLower() != ".png") {
                    continue;
                }
                string dt = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                filename += dt + file.FileName;
                try {
                    file.SaveAs(location + filename);
                    ds_hinhanh photo = new ds_hinhanh() {
                        id_ablum = album.id_ablum,
                        tenhinh = filename
                    };
                    db.ds_hinhanh.AddObject(photo);
                } catch { continue; }
            }
            db.SaveChanges();

            //update Session
            var photos = db.ds_hinhanh.Where(i => i.id_ablum == album.id_ablum);
            foreach (ds_hinhanh p in photos) {
                if (!album.HinhAnh.Exists(i => i.id_hinhanh == p.id_hinhanh)) {
                    SaleSoft.Models.BaseClient.ds_hinhanh basePhoto = new Models.BaseClient.ds_hinhanh();
                    ObjectHelper.Copy(p, basePhoto);
                    album.HinhAnh.Add(basePhoto);
                }
            }
        }

        [HttpPost]
        [GridAction]
        public ActionResult _UpdatePhotoInfo ( [Bind(Prefix = "updated")]IEnumerable<SaleSoft.Models.BaseClient.ds_hinhanh> updated,
                                               [Bind(Prefix = "deleted")]IEnumerable<SaleSoft.Models.BaseClient.ds_hinhanh> deleted ) {
            SaleSoft.Models.BaseClient.ds_album album = (SaleSoft.Models.BaseClient.ds_album)Session[ScreenClientConstants.CURRENT_ALBUM];
            if (updated != null) {
                foreach (SaleSoft.Models.BaseClient.ds_hinhanh u in updated) {
                    var target = album.HinhAnh.SingleOrDefault(i => i.id_hinhanh == u.id_hinhanh);
                    if (target != null) {
                        target.tenhinh = u.tenhinh;
                        target.sothutu = u.sothutu;
                        //save to database
                        ds_hinhanh p = new ds_hinhanh();
                        ObjectHelper.Copy(target, p);
                        db.ds_hinhanh.Attach(p);
                        db.ObjectStateManager.ChangeObjectState(p, EntityState.Modified);
                    }
                }
            }

            if (deleted != null) {
                foreach (SaleSoft.Models.BaseClient.ds_hinhanh d in deleted) {
                    var target = album.HinhAnh.SingleOrDefault(i => i.id_hinhanh == d.id_hinhanh);
                    if (target != null) {
                        try {
                            string filePath = Server.MapPath("~\\UploadImages\\") + target.tenhinh;
                            FileHelper.DeleteFile(filePath);
                        } catch { }
                        album.HinhAnh.Remove(target);
                        //remove from database                        
                        ds_hinhanh p = db.ds_hinhanh.SingleOrDefault(i => i.id_hinhanh == d.id_hinhanh);
                        if (p != null) {
                            db.ds_hinhanh.DeleteObject(p);
                        }

                    }
                }
            }

            db.SaveChanges();
            return View(new GridModel(album.HinhAnh));
        }
        #endregion

        #region Helper Section
        //private void SearchAlbum ( PhotoAlbumScreen screen ) {
        //    var albums = db.PhotoAlbums.Where(i => (screen.AlbumName.Equals(string.Empty) || i.Name.Contains(screen.AlbumName))
        //                                        && (screen.PostedDate == null || i.DatePosted >= screen.PostedDate)
        //                                        && i.IsActive == screen.Active);
        //    List<SampleShop.Models.BaseClient.PhotoAlbum> listAlbum = new List<Models.BaseClient.PhotoAlbum>();
        //    foreach (PhotoAlbum album in albums) {
        //        SampleShop.Models.BaseClient.PhotoAlbum baseAlbum = new Models.BaseClient.PhotoAlbum();
        //        ObjectHelper.Copy(album, baseAlbum);
        //        baseAlbum.canDel = album.Photos.Count > 0 ? false : true;
        //        listAlbum.Add(baseAlbum);
        //    }
        //    screen.Albums = listAlbum;
        //}
        #endregion

        #region Additional Section
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        #endregion
    }
}